package com.xm.adv.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.xm.adv.Ctr.OpenCloseCtr;
import com.xm.adv.R;
import com.xm.adv.bean.OpenCloseBean;
import com.xm.adv.view.dialog.TimeDialog;
import com.xm.adv.viewholder.OpenCloseViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.text.ParseException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xinya.com.baselibrary.baseactivity.ZjbBaseActivity;
import xinya.com.baselibrary.constant.Constant;
import xinya.com.baselibrary.easyrecyclerview.EasyRecyclerView;
import xinya.com.baselibrary.easyrecyclerview.adapter.BaseViewHolder;
import xinya.com.baselibrary.easyrecyclerview.adapter.RecyclerArrayAdapter;
import xinya.com.baselibrary.eventbus.EventBusMsg;
import xinya.com.baselibrary.router.RouterUrl;
import xinya.com.baselibrary.utils.ACacheX;
import xinya.com.baselibrary.utils.DateTransforam;
import xinya.com.baselibrary.utils.LogUtil;
import xinya.com.baselibrary.utils.ToastUtils;
import xinya.com.baselibrary.utils.gson.GenericType;
import xinya.com.baselibrary.utils.gson.GsonUtils;
import xinya.com.baselibrary.view.decoration.LineDividerItemDecoration;

@Route(path = RouterUrl.Set.set_openClose)
public class OpenCloseTimeActivity extends ZjbBaseActivity {

    @BindView(R.id.imageBack)
    ImageView imageBack;
    @BindView(R.id.textViewTitle)
    TextView textViewTitle;
    @BindView(R.id.textViewRight)
    TextView textViewRight;
    @BindView(R.id.line)
    TextView line;
    @BindView(R.id.viewBar)
    LinearLayout viewBar;
    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    @BindView(R.id.btnClear)
    Button btnClear;
    @BindView(R.id.btnSave)
    Button btnSave;
    private RecyclerArrayAdapter<OpenCloseBean> adapter;
    private TimeDialog timeDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_open_close_time);
        ButterKnife.bind(this);
        init();
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {

    }

    @Override
    protected void initViews() {
        textViewTitle.setText("定时开关机");
    }

    @Override
    protected void initRecyclerview() {
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.addItemDecoration(new LineDividerItemDecoration(mContext, 8, 0));
        recyclerView.setRefreshingColorResources(R.color.basic_color);
        recyclerView.getSwipeToRefresh().setProgressViewOffset(true, 0, 190);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter<OpenCloseBean>(mContext) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                int layout = R.layout.item_open_close;
                return new OpenCloseViewHolder(parent, layout);
            }
        });
        adapter.setOnItemClickListener(position -> {
            if (timeDialog != null) {
                timeDialog.dismiss();
                timeDialog = null;
            }
            timeDialog = new TimeDialog(mContext, adapter.getItem(position), (hourStart, mintuneStart, hourEnd, mintuneEnd) -> {
                adapter.getItem(position).setStartTime(hourStart + ":" + mintuneStart);
                adapter.getItem(position).setEndTime(hourEnd + ":" + mintuneEnd);
                adapter.notifyItemChanged(position);
            });
            timeDialog.show();
        });
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
        String closeOpenTime = ACacheX.getAsString(mContext, Constant.AcacheKey.setInfo, Constant.AcacheValue.closeOpenTime);
        adapter.clear();
        if (TextUtils.isEmpty(closeOpenTime)) {
            adapter.add(new OpenCloseBean("00:00", "00:00"));
            adapter.add(new OpenCloseBean("00:00", "00:00"));
            adapter.add(new OpenCloseBean("00:00", "00:00"));
            adapter.notifyDataSetChanged();
        } else {
            LogUtil.LogShitou("OpenCloseTimeActivity--initData", ""+closeOpenTime);
            try {
                List<OpenCloseBean> httpResult = GsonUtils.parseToGenericObject(closeOpenTime, new GenericType<List<OpenCloseBean>>() {
                });
                adapter.addAll(httpResult);
            } catch (Exception e) {
                showError(recyclerView, "数据出错");
            }
        }
    }

    @OnClick({R.id.imageBack, R.id.btnClear, R.id.btnSave})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.imageBack:
                onBackPressed();
                break;
            case R.id.btnClear:
                break;
            case R.id.btnSave:
                List<OpenCloseBean> allData = adapter.getAllData();
                int num = 0;
                try {
                    for (int i = 0; i < allData.size(); i++) {
                        long startTime = DateTransforam.dateToStampXXX(allData.get(i).getStartTime());
                        if (TextUtils.equals("00:00", allData.get(i).getStartTime()) && TextUtils.equals("00:00", allData.get(i).getEndTime())) {
                            num++;
                        } else {
                            for (int j = 0; j < allData.size(); j++) {
                                long endTime = DateTransforam.dateToStampXXX(allData.get(i).getEndTime());
                                if (Math.abs(startTime - endTime) <= 5 * 60 * 1000L) {
                                    ToastUtils.showToast(mContext, "开机时间和关机时间之差要大于5分钟");
                                    return;
                                }
                            }
                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (num == allData.size()) {
                    ToastUtils.showToast(mContext, "请至少设置一组开关机时间");
                    return;
                }
                LogUtil.LogShitou("OpenCloseTimeActivity--onViewClicked", ""+GsonUtils.parseObject(allData));
                ACacheX.putAsString(mContext, Constant.AcacheKey.setInfo, Constant.AcacheValue.closeOpenTime, GsonUtils.parseObject(allData));
                OpenCloseCtr.init(mContext);
                EventBus.getDefault().post(new EventBusMsg(Constant.EventKey.setCloseOpenTime));
                finish();
                break;
        }
    }
}
